<template>
  <div class="projectContainer">
    <learnProjectDetail
      v-model:currentData="currentData"
      @handleClick="handleClick"
    />

    <a-modal
      :maskClosable="false"
      width="800px"
      v-model:open="modal.visible"
      :ok-button-props="{ disabled: modal.formDisable }"
      :footer="null"
    >
      <addAndEditLearnProject
        v-model="formModel"
        @handleSubmit="handleSubmit"
        @handleCancel="modal.visible = false"
        :disabled="modal.formDisable"
      />
    </a-modal>
    <a-modal
      :title="t('modal', '上传相关(推荐使用txt文件)')"
      :maskClosable="false"
      width="500px"
      v-model:open="filesModal.visible"
      @ok="handleFilesSubmit">
      <div class="filesBox">
        <minFile
          :accept="accept"
          name="知识大纲"
          @handleReadFile="handleReadFile"
        >
          <div class="fileBtn" :style="{ cursor: filesModal.record['知识大纲'].loading ? 'not-allowed' : 'pointer' }">
            <LoadingOutlined v-if="filesModal.record['知识大纲'].loading" />
            <UploadOutlined v-else />
              {{t('modal', '知识大纲')}}
          </div>
        </minFile>
        <div class="file" v-if="filesModal.record['知识大纲'].name">
          <div style="cursor: pointer;" @click="handleClick({name: '相关资料下载', record: filesModal.record['知识大纲']})">
            {{ filesModal.record['知识大纲'].name }}
          </div>
          <DeleteOutlined @click="handleClick({name: '删除知识大纲'})" />
        </div>
        <minFile
          :accept="accept"
          name="测试题"
          @handleReadFile="handleReadFile"
        >
          <div class="fileBtn" :style="{ cursor: filesModal.record['测试题'].loading ? 'not-allowed' : 'pointer' }">
            <LoadingOutlined v-if="filesModal.record['测试题'].loading" />
            <UploadOutlined v-else />
            {{t('modal', '测试题')}}
          </div>
        </minFile>
        <div class="file" v-if="filesModal.record['测试题'].name">
          <div style="cursor: pointer;" @click="handleClick({name: '相关资料下载', record: filesModal.record['测试题']})">
            {{ filesModal.record['测试题'].name }}
          </div>
          <DeleteOutlined @click="handleClick({name: '删除测试题'})" />
        </div>
      </div>
    </a-modal>
    
  </div>
</template>
<script setup>
import learnProjectDetail from '@/components/student/learnProjectDetail.vue'
import addAndEditLearnProject from '@/components/learn/addAndEditLearnProject.vue'
import { LoadingOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { ref, reactive, inject, onMounted } from 'vue'
import {
  learningFindById,
  learningModify,
} from '@/request/teacher/project/learn'
import { learningMaterialFileGet, learningMaterialFileUpload, learningMaterialFileSave } from '@/request/learn/project'
import { message } from 'ant-design-vue'
import MarkdownIt from 'markdown-it'
import minFile from '@/components/common/minFile.vue'
import { t } from '@/i18n'

const accept = '.txt,.doc,.docx,.md'
const loading = ref(false)
const modal = reactive({ visible: false, formDisable: false, name: '' })
const formModel = ref({ projectJobDTOList: [{}] })
let pojectInfo = JSON.parse(sessionStorage.getItem('pojectInfo') || '{}')
const currentData = ref({})
function markdownIt() {
  const md = new MarkdownIt()
  if (
    currentData.value.describe &&
    currentData.value.describe.includes('###')
  ) {
    currentData.value.describe = md.render(currentData.value.describe)
  }
  if (
    currentData.value.scoreStandard &&
    currentData.value.scoreStandard.includes('###')
  ) {
    currentData.value.scoreStandard = md.render(currentData.value.scoreStandard)
  }
  if (currentData.value.target && currentData.value.target.includes('###')) {
    currentData.value.target = md.render(currentData.value.target)
  }
}

// onMounted(()=>{
// 	show()
// 	markdownIt()
// 	console.log('currentData.value',currentData.value)
// })

const show = async () => {
  let req = {
    ...pojectInfo,
  }
  let res = await learningFindById(req)
  if (!res) return
  currentData.value = res.data
  markdownIt()
  console.log('currentData.value', currentData.value)
}
show()

// const downloadFile = (fileUrl, fileName) => {
//   const a = document.createElement('a')
//   a.href = fileUrl
//   a.download = fileName || 'default'
//   document.body.appendChild(a)
//   a.click()
//   document.body.removeChild(a)
// }
// const downloadFileFromFetch = async (u, fileName) => {
//   const response = await fetch(u);
//   const blob = await response.blob();
//   const url = window.URL.createObjectURL(blob);
//   const a = document.createElement('a');
//   a.href = url;
//   a.download = fileName;
//   document.body.appendChild(a);
//   a.click();
//   window.URL.revokeObjectURL(url);
//   document.body.removeChild(a);
// }
const currentItem = ref({})
const handleClick = async ({ name, item, record }) => {
  let req = { ...item }
  let res = null
  let operate = null
  switch (name) {
    case '编辑':
      currentItem.value = { ...item }
      formModel.value = {
        ...item,
        course: item?.courseList?.map((val) => val.course),
        gradeClass: item?.gradeClassList?.map((val) => val.gradeClass),
        projectJobDTOList: item?.projectJobList || [{}],
        coTeacherIds: item?.coTeacherList?.map((val) => val.teacherId) || [],
        mainTeacherId: item?.mainTeacher?.teacherId,
      }
      modal.visible = true
      modal.formDisable = false
      modal.name = t('common','编辑')
      break
    case '上传相关资料':
      currentItem.value = { ...item }
      res = await learningMaterialFileGet(item.id)
      if (!res) return
      formatFilesRecord(res.data)
      filesModal.visible = true
      break
    case '相关资料下载':
      // downloadFile(record.fileUrl, record.name)
			window.open(record?.fileUrl)
			break
    case '删除知识大纲':
    case '删除测试题':
      filesModal.record[name.replace('删除', '')] = {}
			break
  }
}
const handleSubmit = async (val) => {
  let req = {
    ...val,
    course: val?.course?.join(),
    gradeClass: val?.gradeClass?.join(),
  }
  loading.value = true
  let res = await learningModify(req)
  loading.value = false
  if (!res) return
  modal.visible = false
  message.success(t('common','保存成功'))
  show()
}

const filesModal = reactive({ visible: false, formDisable: false, name: '', record: {} })
const handleReadFile = async (e) => {
  console.log(filesModal.record, e.name, '??')
  if (e.message) return message.error(e.message)
  filesModal.record[e.name].loading = true
  let res = await learningMaterialFileUpload(e.name == '知识大纲' ? 0 : 1, currentItem.value.id, { file: e.file })
  filesModal.record[e.name].loading = false
  if (!res) return
  message.success(t('common','上传成功'))
  filesModal.record[e.name] = res.data
}
const formatFilesRecord =  (list) => {
  filesModal.record['知识大纲'] = list?.filter(val => val.type == 0)[0] || {}
  filesModal.record['测试题'] = list?.filter(val => val.type == 1)[0] || {}
}
const handleFilesSubmit = async () => {
  console.log(currentItem.value, 'currentItem.value')
  let array = [
    filesModal.record['知识大纲'],
    filesModal.record['测试题'],
  ]
  loading.value = true
  let res = await learningMaterialFileSave(currentItem.value.id, array.filter(val => val.path))
  loading.value = false
  if (!res) return
  filesModal.visible = false
  message.success(t('common','保存成功'))
  show()
}

</script>

<style lang="scss" scoped>
.projectContainer {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
}
.filesBox {
  padding: 25px 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  .file {
    width: 100%;
    /* height: 35px; */
    background: #f5f5f5;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
  }
}
.fileBtn { 
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  padding: 6px 13px;
  cursor: pointer;
  background-color: #ffffff;
  color: rgba(0, 0, 0, 0.88);
  border:1px solid #d9d9d9;
  span {
    margin-right: 10px;
  }
}
</style>
